<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import CdlForm from "@/components/form";
import type {FormTree} from "@/interfaces/components/Form";
import type {FormData} from "@/interfaces/components/Page";
import {Extra, Plugin, Vehicle} from "@/interfaces/views/vehicle/vehicle";
import {ref} from "vue";
import {appStore} from "@/store/modules/app";
import {
  useCreateVehicleApi,
  useGetDriverSelect,
  useGetVehicleInfoApi,
  useUpdateVehicleApi
} from "@/api/vehicle/vehicle";
import {ElMessage} from "element-plus";
import {mergeObjects} from "@/utils/utilities";
import constant from "@/utils/constant";

const router = useRouter()
const route = useRoute()
const store = appStore()
if(route.query.id) initData()

const basicFormTree: FormTree<Vehicle> = [
    [
      {label: "车牌号码", prop: "licensePlate", component: "input", rule: [
          {required: true, message: '车牌号码不能为空', trigger: 'blur'}
        ]},
      {label: "司机名字", prop: "driverId", component: "select", serviceOptionKey: "driverArr",
        optionProps: {label: "name", value: "id"}},
      {label: "车架号", prop: "vin", component: "input"}
    ],
    [
      {label: "使用性质", prop: "nature", component: "select", options: store.getDict("vehicle_nature"),
        optionProps: {label: "dictLabel", value: "dictValue"}},
      {label: "车型", prop: "type", component: "select"},
      {label: "车辆颜色", prop: "color", component: "input"},
    ],
    [
      {label: "发动机编号", prop: "engineNum", component: "input"},
      {label: "车辆所有人", prop: "owner", component: "input"},
      {label: "核定载质量", prop: "ratifiedLoad", component: "input"},
    ],
    [
      {label: "车辆能源类型", prop: "energyType", component: "select", options: store.getDict("vehicle_type"),
        optionProps: {label: "dictLabel", value: "dictValue"}},
      {label: "总质量", prop: "totalMass", component: "input"},
      {label: "外廓尺寸", prop: "size", component: "input"},
    ],
    [
      {label: "行驶证", prop: "travelLicenseNum", component: "input"},
      {label: "参考油耗(L/100KM)", prop: "fuelConsumption", component: "input"},
      {label: "行驶证档案编号", prop: "travelLicenseFileNum", component: "input"},
    ],
    [
      {label: "车辆道路运输许可证", prop: "transportPermit", component: "input"},
    ],
    [
      {label: "备注", prop: "remark", type: "textarea", component: "input", style: "width: 500px"},
    ]
]
const pluginFormTree: FormTree<Plugin> = [
    [
      {label: "IMEI/SN码", prop: "imei", component: "input"}
    ]
]
const extraTableTree: FormTree<Extra> = [
    [
      {label: "行驶证照片", prop: "travelLicenseImg", component: "upload", action: constant.uploadUrl},
      {label: "道路运输证照片", prop: "transportPermitImg", component: "upload", action: constant.uploadUrl},
      {label: "运营许可证照片", prop: "operatingLicenseImg", component: "upload", action: constant.uploadUrl}
    ]
]

const basicData = ref<FormData<Vehicle>>({
  licensePlate: "",
  driverName: "",
  driverId: undefined,
  vin: "",
  nature: undefined,
  type: "",
  color: "",
  engineNum: "",
  owner: "",
  ratifiedLoad: "",
  energyType: undefined,
  totalMass: "",
  size: "",
  travelLicenseNum: "",
  fuelConsumption: "",
  travelLicenseFileNum: "",
  transportPermit: "",
  remark: "",
})
const pluginData = ref<FormData<Plugin>>({
  imei: ""
})
const extraData = ref<FormData<Extra>>({
  travelLicenseImg: "",
  transportPermitImg: "",
  operatingLicenseImg: "",
  otherImg: "",
})
const basicEl = ref()
const pluginEl = ref()
const extraEl = ref()
let driverArr: any[] = []
function getDriverArr(){
  return new Promise((resolve, reject) => {
    useGetDriverSelect().then(res =>{
      driverArr.push(...res.data)
      resolve(driverArr)
    })
  })
}

/**
 * 提交
 */
async function submit(){
  const basic = await basicEl.value.parentSubmit()
  const plugin = await pluginEl.value.parentSubmit()
  const extra = await extraEl.value.parentSubmit()
  const data: {[key: string]: any} = {}
  Object.assign(data, basic, plugin, extra)
  for (let i = 0; i < driverArr.length; i++) {
    if(driverArr[i].id === data.driverId) {
      data.driverName = driverArr[i].name
      break
    }
  }
  if(route.query.id){
    data.id = route.query.id
    useUpdateVehicleApi(data).then((res: any) => {
        ElMessage.success("修改成功，自动返回上一页")
      fallbackPage()
    })
  }else {
    useCreateVehicleApi(data).then((res: any) =>{
        ElMessage.success("创建成功，自动返回上一页")
      fallbackPage()
    })
  }
}
/**
 * 初始化数据
 */
function initData(){
  useGetVehicleInfoApi(route.query.id as string | number).then((res: any) => {
    const {imei, travelLicenseImg, transportPermitImg, operatingLicenseImg, otherImg, ...rest} = res.data
    mergeObjects(basicData.value, rest)
    pluginData.value.imei =  imei
    extraData.value = {
      "travelLicenseImg": travelLicenseImg,
      "transportPermitImg": transportPermitImg,
      "operatingLicenseImg": operatingLicenseImg,
      "otherImg": otherImg
    }
    driverArr.push({
      id: rest.driverId,
      name: rest.driverName
    })
  })
}

/**
 * 回退页面
 */
function fallbackPage(){
  router.back()
}
</script>

<template>
<el-card style="position: relative">
  <button class="back_btn" @click="fallbackPage"></button>
  <h1 class="top_line">基础信息</h1>
  <el-divider></el-divider>
  <CdlForm :model="basicData" :template-tree="basicFormTree" ref="basicEl" label-width="150"
           :init="{driverArr: getDriverArr}"></CdlForm>
  <h1>车载硬件信息</h1>
  <el-divider></el-divider>
  <CdlForm :model="pluginData" :template-tree="pluginFormTree" ref="pluginEl"></CdlForm>
  <h1>附加信息</h1>
  <el-divider></el-divider>
  <CdlForm :model="extraData" :template-tree="extraTableTree" ref="extraEl" label-width="110"></CdlForm>
  <div class="footer_btn">
    <el-button type="primary" @click="submit">提交</el-button>
  </div>
</el-card>
</template>
